package org.springblade.common.config;

import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * P6Spy自定义日志格式化器
 * 
 * @author Jackey
 * @since 2024-11-15
 */
public class P6SpyFormatter implements MessageFormattingStrategy {

  /**
   * 日期格式
   */
  private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

  @Override
  public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql,
      String url) {
    // 如果SQL为空，直接返回空字符串
    if (StringUtils.isEmpty(sql)) {
      return StringUtils.EMPTY;
    }

    return String.format("[P6Spy] %s | %s ms | %s | %s | %s",
        DATE_FORMAT.format(new Date()),
        elapsed,
        category,
        connectionId,
        getSqlString(prepared, sql));
  }

  /**
   * 获取格式化后的SQL字符串
   * 
   * @param prepared 预编译SQL
   * @param sql      实际SQL
   * @return 格式化后的SQL字符串
   */
  private String getSqlString(String prepared, String sql) {
    if (StringUtils.isNotEmpty(prepared)) {
      return prepared;
    }
    if (StringUtils.isNotEmpty(sql)) {
      return sql;
    }
    return StringUtils.EMPTY;
  }
}